package top.itpath.common.util;

import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 请求参数获取工具类
 *
 * @author zhaomengru
 * @time 2023/10/10 - 23:25
 */
public class RequestUtil {

    public static String getToken() {
        ServletRequest servletRequest = Objects.requireNonNull(getRequest());
        return getToken((HttpServletRequest) servletRequest);
    }

    public static String getToken(HttpServletRequest request) {
        String token = request.getParameter("token");
        if (StringUtils.hasText(token)) {
            return token;
        }
        token = request.getHeader("token");
        if (StringUtils.hasText(token)) {
            return token;
        }
        return (String) request.getAttribute("token");
    }

    public static ServletRequest getRequest() {
        // 从RequestContextHolder中获取request
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }
        return requestAttributes.getRequest();
    }
}
